package com.kingwang.study.spring.security.demo.security.handler;

import com.kingwang.study.spring.security.demo.security.dto.AuthenticationResult;
import com.kingwang.study.spring.security.demo.util.HttpServletUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token认证失败的处理器
 */
public class JsonResponseAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        AuthenticationResult result = new AuthenticationResult();
        result.setSuccess(false);
        result.setMessage("认证失败：" + exception.getMessage());

        HttpServletUtils.sendJsonContentResponse(response, HttpStatus.UNAUTHORIZED, result);
    }
}
